<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Druid ResultSet 内存泄露分析现象在使用 ShardingSphere-JDBC 配置 Druid 连接池，通过 Jmeter 开启预编译缓存进行性能压测时，遇到压测性波动较大问题。 定位流程问题分析压测过程中通过 jstat 观测 GC 情况，存在频繁 GC。通过 async profiler 抓取 cpu 火焰图观察，发现大量 CPU 消耗在 GC 线程上，真正执行业务代码的 C">
<meta property="og:type" content="article">
<meta property="og:title" content="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">
<meta property="og:url" content="https://flyingzc.github.io/articles/druid/druid01-resultset-leak.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="Druid ResultSet 内存泄露分析现象在使用 ShardingSphere-JDBC 配置 Druid 连接池，通过 Jmeter 开启预编译缓存进行性能压测时，遇到压测性波动较大问题。 定位流程问题分析压测过程中通过 jstat 观测 GC 情况，存在频繁 GC。通过 async profiler 抓取 cpu 火焰图观察，发现大量 CPU 消耗在 GC 线程上，真正执行业务代码的 C">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2025-06-30T16:00:00.000Z">
<meta property="article:modified_time" content="2025-07-04T03:13:46.067Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="Druid">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析",
  "url": "https://flyingzc.github.io/articles/druid/druid01-resultset-leak.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2025-06-30T16:00:00.000Z",
  "dateModified": "2025-07-04T03:13:46.067Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/druid/druid01-resultset-leak.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-07-04T03:13:46.067Z" title="更新于 2025-07-04 11:13:46">2025-07-04</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Druid/">Druid</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="Druid-ResultSet-内存泄露分析"><a href="#Druid-ResultSet-内存泄露分析" class="headerlink" title="Druid ResultSet 内存泄露分析"></a>Druid ResultSet 内存泄露分析</h1><h2 id="现象"><a href="#现象" class="headerlink" title="现象"></a>现象</h2><p>在使用 ShardingSphere-JDBC 配置 Druid 连接池，通过 Jmeter 开启预编译缓存进行性能压测时，遇到压测性波动较大问题。</p>
<h2 id="定位流程"><a href="#定位流程" class="headerlink" title="定位流程"></a>定位流程</h2><h3 id="问题分析"><a href="#问题分析" class="headerlink" title="问题分析"></a>问题分析</h3><p>压测过程中通过 jstat 观测 GC 情况，存在频繁 GC。<br>通过 async profiler 抓取 cpu 火焰图观察，发现大量 CPU 消耗在 GC 线程上，真正执行业务代码的 CPU 占比较少。</p>
<p>压测过程中通过 jmap 执行堆 Dump，通过 Eclipse MAT 分析堆 Dump。<br>查看支配树，压测使用 50 个线程时，存在 50 个 DruidPooledPreparedStatement 实例，但是 DruidPooledPreparedStatement 深堆大小共 1G。<br>每个 DruidPooledPreparedStatement#resultSetTrace 里持有大量 result set 实例。<br>至此，确定 DruidPooledPreparedStatement#resultSetTrace 内存泄漏。</p>
<h3 id="问题复现"><a href="#问题复现" class="headerlink" title="问题复现"></a>问题复现</h3><h4 id="使用-druid-jdbc-demo-复现问题"><a href="#使用-druid-jdbc-demo-复现问题" class="headerlink" title="使用 druid jdbc demo 复现问题"></a>使用 druid jdbc demo 复现问题</h4><p>使用 Druid 原生最小 Demo 复现问题。<br>测试： 同一个 PreparedStatement 在执行 executeQuery 查询后,多次通过 getResultSet 获取结果集,最后关闭。<br>现象：只要连续拿结果集，再 close 就会泄露，因为 Druid 代码里每次就只判断最后一个是不是close。<br>多次执行后 DruidPooledPreparedStatement#resultSetTrace 缓存没有清理，发生内存泄漏。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><code class="hljs Java"><span class="hljs-keyword">import</span> com.alibaba.druid.pool.DruidDataSource;<br><span class="hljs-keyword">import</span> com.alibaba.druid.pool.DruidPooledPreparedStatement;<br><span class="hljs-keyword">import</span> org.junit.Test;<br><br><span class="hljs-keyword">import</span> java.lang.reflect.Field;<br><span class="hljs-keyword">import</span> java.sql.Connection;<br><span class="hljs-keyword">import</span> java.sql.PreparedStatement;<br><span class="hljs-keyword">import</span> java.sql.ResultSet;<br><span class="hljs-keyword">import</span> java.sql.SQLException;<br><span class="hljs-keyword">import</span> java.util.List;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 前置: 通过 mysql 执行如下 sql,然后运行测试.</span><br><span class="hljs-comment"> * create database test;</span><br><span class="hljs-comment"> * create table test_druid(id int, name varchar(25));</span><br><span class="hljs-comment"> * insert into test.test_druid values(1,1),(2,2),(3,3),(4,4),(5,5);</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">DruidMySQLDemo</span> &#123;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">URL</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;jdbc:mysql://localhost:3306/test&quot;</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">USER</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;root&quot;</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">PASSWORD</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;root&quot;</span>;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 内存泄露异常Case: 测试结果集对象 resultSetTrace 的泄漏.</span><br><span class="hljs-comment">     * 同一个 PreparedStatement 在执行 executeQuery 查询后,多次通过 getResultSet 获取结果集,最后关闭.多次执行后 DruidPooledPreparedStatement#resultSetTrace 缓存没有清理</span><br><span class="hljs-comment">     * </span><br><span class="hljs-comment">     * <span class="hljs-doctag">@throws</span> Exception </span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testResultSetTraceLeak</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-type">Connection</span> <span class="hljs-variable">connection</span> <span class="hljs-operator">=</span> getConnection();<br>        <span class="hljs-type">String</span> <span class="hljs-variable">sql</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;SELECT * FROM test_druid WHERE id = ?&quot;</span>;<br>        <span class="hljs-type">PreparedStatement</span> <span class="hljs-variable">psmt</span> <span class="hljs-operator">=</span> connection.prepareStatement(sql);<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100</span>; i++) &#123;<br>            psmt.setInt(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);<br>            <span class="hljs-type">ResultSet</span> <span class="hljs-variable">resultSet</span> <span class="hljs-operator">=</span> psmt.executeQuery();<br>            <span class="hljs-type">ResultSet</span> <span class="hljs-variable">rs1</span> <span class="hljs-operator">=</span> psmt.getResultSet();<br>            <span class="hljs-type">ResultSet</span> <span class="hljs-variable">rs2</span> <span class="hljs-operator">=</span> psmt.getResultSet();<br>            <span class="hljs-type">ResultSet</span> <span class="hljs-variable">rs3</span> <span class="hljs-operator">=</span> psmt.getResultSet();<br>            <span class="hljs-type">ResultSet</span> <span class="hljs-variable">rs4</span> <span class="hljs-operator">=</span> psmt.getResultSet();<br>            <span class="hljs-type">ResultSet</span> <span class="hljs-variable">rs5</span> <span class="hljs-operator">=</span> psmt.getResultSet();<br>            rs1.close();<br>            rs2.close();<br>            rs3.close();<br>            rs4.close();<br>            rs5.close();<br>            resultSet.close();<br>        &#125;<br>        <span class="hljs-comment">// 501 缓存没有清理</span><br>        printResultSetTraceFieldSize(psmt);<br>        psmt.close();<br>        <span class="hljs-comment">// 0</span><br>        printResultSetTraceFieldSize(psmt);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 正常测试case.</span><br><span class="hljs-comment">     * </span><br><span class="hljs-comment">     * <span class="hljs-doctag">@throws</span> Exception </span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testOK</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-type">Connection</span> <span class="hljs-variable">connection</span> <span class="hljs-operator">=</span> getConnection();<br>        <span class="hljs-type">String</span> <span class="hljs-variable">sql</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;SELECT * FROM test_druid WHERE id = ?&quot;</span>;<br>        <span class="hljs-type">PreparedStatement</span> <span class="hljs-variable">psmt</span> <span class="hljs-operator">=</span> connection.prepareStatement(sql);<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100</span>; i++) &#123;<br>            psmt.setInt(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);<br>            <span class="hljs-type">ResultSet</span> <span class="hljs-variable">resultSet</span> <span class="hljs-operator">=</span> psmt.executeQuery();<br>            resultSet.close();<br>        &#125;<br>        <span class="hljs-comment">// 1</span><br>        printResultSetTraceFieldSize(psmt);<br>        psmt.close();<br>        <span class="hljs-comment">// 0</span><br>        printResultSetTraceFieldSize(psmt);<br>    &#125;<br>    <br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Connection <span class="hljs-title function_">getConnection</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> ClassNotFoundException, SQLException &#123;<br>        Class.forName(<span class="hljs-string">&quot;com.alibaba.druid.pool.DruidDataSource&quot;</span>);<br>        <span class="hljs-type">DruidDataSource</span> <span class="hljs-variable">dataSource</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">DruidDataSource</span>();<br>        dataSource.setUrl(URL);<br>        dataSource.setUsername(USER);<br>        dataSource.setPassword(PASSWORD);<br>        <span class="hljs-keyword">return</span> dataSource.getConnection();<br>    &#125;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">printResultSetTraceFieldSize</span><span class="hljs-params">(<span class="hljs-keyword">final</span> PreparedStatement psmt)</span> <span class="hljs-keyword">throws</span> IllegalAccessException &#123;<br>        Class&lt;?&gt; currentClass = DruidPooledPreparedStatement.class;<br>        <span class="hljs-type">Field</span> <span class="hljs-variable">field</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;<br>        <span class="hljs-keyword">while</span> (currentClass != <span class="hljs-literal">null</span>) &#123;<br>            <span class="hljs-keyword">try</span> &#123;<br>                field = currentClass.getDeclaredField(<span class="hljs-string">&quot;resultSetTrace&quot;</span>);<br>                <span class="hljs-keyword">if</span> (field != <span class="hljs-literal">null</span>) &#123;<br>                    <span class="hljs-keyword">break</span>;<br>                &#125;<br>            &#125; <span class="hljs-keyword">catch</span> (NoSuchFieldException e) &#123;<br>                currentClass = currentClass.getSuperclass();<br>            &#125;<br>        &#125;<br>        field.setAccessible(<span class="hljs-literal">true</span>);<br>        List&lt;String&gt; resultSetTrace = (List&lt;String&gt;) field.get(psmt);<br>        System.out.println(<span class="hljs-string">&quot;resultSetTrace size: &quot;</span> + resultSetTrace.size());<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="Druid-相关代码"><a href="#Druid-相关代码" class="headerlink" title="Druid 相关代码"></a>Druid 相关代码</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// com.alibaba.druid.pool.DruidPooledStatement#addResultSetTrace</span><br><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">addResultSetTrace</span><span class="hljs-params">(ResultSet resultSet)</span> &#123;<br>    <span class="hljs-keyword">if</span> (resultSetTrace == <span class="hljs-literal">null</span>) &#123;<br>        resultSetTrace = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;ResultSet&gt;(<span class="hljs-number">1</span>);<br>    &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (resultSetTrace.size() &gt; <span class="hljs-number">0</span>) &#123;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">lastIndex</span> <span class="hljs-operator">=</span> resultSetTrace.size() - <span class="hljs-number">1</span>;<br>        <span class="hljs-comment">// 1.每次只会判断缓存中的最后一个结果集</span><br>        <span class="hljs-type">ResultSet</span> <span class="hljs-variable">lastResultSet</span> <span class="hljs-operator">=</span> resultSetTrace.get(lastIndex);<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 1.1.只有当最后一个结果集是 closed, 才会更新 resultSetTrace 缓存</span><br>            <span class="hljs-keyword">if</span> (lastResultSet.isClosed()) &#123;<br>                resultSetTrace.set(lastIndex, resultSet);<br>                <span class="hljs-keyword">return</span>;<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (SQLException ex) &#123;<br>            <span class="hljs-comment">// skip</span><br>        &#125;<br>    &#125;<br>    <span class="hljs-comment">// 1.2.否则,就会将结果集加入 resultSetTrace 缓存</span><br>    resultSetTrace.add(resultSet);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>代码可见，只要有一个 preparedStatement 下的连续获取多次 result set 并且没有关闭，就会产生 resultSetTrace 泄漏。</p>
<p>给 Druid 提了 issue，反馈该问题:<br><a target="_blank" rel="noopener" href="https://github.com/alibaba/druid/issues/6457">https://github.com/alibaba/druid/issues/6457</a></p>
<h3 id="规避问题"><a href="#规避问题" class="headerlink" title="规避问题"></a>规避问题</h3><p>PreparedStatement 通过 executeQuery 获取结果集后，不要再连续调用 Driud 的 getResultSet 方法，否则就会发生内存泄漏。所以在使用上避免这种场景即可。<br>修复 PR: <a target="_blank" rel="noopener" href="https://github.com/apache/shardingsphere/pull/35853">Reduce the number of getResultSet method calls</a></p>
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/druid/druid01-resultset-leak.html">https://flyingzc.github.io/articles/druid/druid01-resultset-leak.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Druid/">Druid</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Druid-ResultSet-%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2%E5%88%86%E6%9E%90"><span class="toc-number">1.</span> <span class="toc-text">Druid ResultSet 内存泄露分析</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%8E%B0%E8%B1%A1"><span class="toc-number">1.1.</span> <span class="toc-text">现象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9A%E4%BD%8D%E6%B5%81%E7%A8%8B"><span class="toc-number">1.2.</span> <span class="toc-text">定位流程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E5%88%86%E6%9E%90"><span class="toc-number">1.2.1.</span> <span class="toc-text">问题分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E5%A4%8D%E7%8E%B0"><span class="toc-number">1.2.2.</span> <span class="toc-text">问题复现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-druid-jdbc-demo-%E5%A4%8D%E7%8E%B0%E9%97%AE%E9%A2%98"><span class="toc-number">1.2.2.1.</span> <span class="toc-text">使用 druid jdbc demo 复现问题</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Druid-%E7%9B%B8%E5%85%B3%E4%BB%A3%E7%A0%81"><span class="toc-number">1.2.3.</span> <span class="toc-text">Druid 相关代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%84%E9%81%BF%E9%97%AE%E9%A2%98"><span class="toc-number">1.2.4.</span> <span class="toc-text">规避问题</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>